package logic

import (
	"context"
	"github.com/zeromicro/go-zero/core/stores/sqlc"
	"gozerogateway/rpc/common/salt"
	"gozerogateway/rpc/model/adminmodel"

	"gozerogateway/rpc/admin/adminclient"
	"gozerogateway/rpc/admin/internal/svc"

	"errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type ChangePwdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewChangePwdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ChangePwdLogic {
	return &ChangePwdLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ChangePwdLogic) ChangePwd(in *adminclient.ChangePwdReq) (*adminclient.ChangePwdResp, error) {
	// todo: add your logic here and delete this line

	userInfo, err := l.svcCtx.AdminModel.FindOneById(l.ctx, in.Id) //Id=1
	switch err {
	case nil:
	case sqlc.ErrNotFound:
		logx.WithContext(l.ctx).Errorf("用户不存在,参数:%d,异常:%s", in.Id, err.Error())
		return nil, errors.New("用户不存在")
	default:
		logx.WithContext(l.ctx).Errorf("密码修改操作未成功,参数:%d,异常:%s", in.Id, err.Error())
		return nil, err
	}

	saltPassword := salt.Saltpassword(userInfo.Salt, in.Password)
	data := &adminmodel.GatewayAdmin{
		Id:       in.Id,
		UserName: userInfo.UserName,
		Salt:     userInfo.Salt,
		Password: saltPassword,
		//CreateAt time.Time `db:"create_at"` // 新增时间
		//UpdateAt time.Time `db:"update_at"` // 更新时间
		IsDelete: 0,
	}
	err = l.svcCtx.AdminModel.Update(l.ctx, data)

	if err != nil {
		logx.WithContext(l.ctx).Errorf("change passowrd error(rpc)")
		return nil, errors.New("change password error(rpc)")
	}
	return &adminclient.ChangePwdResp{
		Isok: "change password ok",
	}, nil
}
